﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using popLib;
using System.Data.EntityClient;
using System.Data.Common;
using System.Configuration;
using PhotoMgr.src.common;
using PhotoMgr.src.gui.photo;

namespace PhotoMgr.src.database
{
    public partial class DBManager
    {
        private static string GenConnectionString()
        {
            var originalConnectionString = ConfigurationManager.ConnectionStrings["PhotoMgrEntities"].ConnectionString;
            var entityBuilder = new EntityConnectionStringBuilder(originalConnectionString);
            var factory = DbProviderFactories.GetFactory(entityBuilder.Provider);
            var providerBuilder = factory.CreateConnectionStringBuilder();

            providerBuilder.ConnectionString = entityBuilder.ProviderConnectionString;

            providerBuilder.Add("Password", "8956148");

            entityBuilder.ProviderConnectionString = providerBuilder.ToString();

            return entityBuilder.ToString();
        }       

        private static ReturnSet ProcessPageData(int page, IQueryable<object> result, int itemPerPage)
        {
            //calculate page data
            var pageData = new PageData();

            if (result.Count() > 0)
            {
                //total pages
                pageData.TotalPages = result.Count() / itemPerPage;
                if (result.Count() % itemPerPage > 0)
                {
                    pageData.TotalPages++;
                }

                //current page
                pageData.CurrentPage = page;
                if (page > pageData.TotalPages)
                {
                    pageData.CurrentPage = pageData.TotalPages;
                }

                //total records
                pageData.TotalRecords = result.Count();

                //get filter record in page
                result = result.Skip((pageData.CurrentPage - 1) * itemPerPage);
                result = result.Take(itemPerPage);
                pageData.DataSource = result.ToList();
            }
            else
            {
                pageData = new PageData(1, 1, result.ToList(), 0);
            }

            return new ReturnSet(true, pageData);
        }

        public static DateTime Get_ServerDateTime()
        {
            using (var entity = new PhotoMgrEntities(GenConnectionString()))
            {
                return entity.sp_Server_GetDateTime().First().Value;
            }
        }

        public static ReturnSet Account_Login(string username, string password)
        {
            using (var entity = new PhotoMgrEntities(GenConnectionString()))
            {
                var rs = entity.Users.Where(x => x.Username == username);
                if (rs.Count() > 0)
                {
                    User acc = rs.First();

                    if (StringLib.MD5(password) == acc.Password)
                    {
                        entity.Detach(acc);
                        return new ReturnSet(true, acc);
                    }
                    else
                        return new ReturnSet(false, Global.DBErrorType.PasswordIsNotCorrect);
                }
                return new ReturnSet(false, Global.DBErrorType.AccountIsNotExisted);
            }
        }

        public static ReturnSet Account_ChangePassword(string username, string oldpassword, string newpassword)
        {

            ReturnSet loginRs = Account_Login(username, oldpassword);

            if (!loginRs.Success)
            {
                return loginRs;
            }

            using (var entity = new PhotoMgrEntities(GenConnectionString()))
            {
                var rs = entity.Users.Where(x => x.Username == username);
                if (rs.Count() > 0)
                {
                    User acc = rs.First();
                    acc.Password = StringLib.MD5(newpassword);
                    entity.SaveChanges();
                    return Account_Login(username, newpassword);
                }
                return new ReturnSet(false, Global.DBErrorType.AccountIsNotExisted);
            }
        }

        public static List<Contest_GetListContestByAdvisor_Result> Contest_GetListContestByAdvisor(int userID)
        {
            using (var entity = new PhotoMgrEntities(GenConnectionString()))
            {
                return entity.Contest_GetListContestByAdvisor(userID).ToList();
            }
        }

        public static List<RoundImage> Contest_FinishRound(int roundID)
        {
            using (var entity = new PhotoMgrEntities(GenConnectionString()))
            {
                return entity.Contest_FinishRound(roundID).ToList();
            }
        }

        public static List<View_RoundImage> Round_ListImage(int roundID, ScoreType scoretype)
        {
            using (var entity = new PhotoMgrEntities(GenConnectionString()))
            {
                int type = Convert.ToInt16(scoretype);
                return entity.Round_ListImage(roundID, type).ToList();
            }
        }

        public static List<View_ContestUserSetting> Contest_GetContestUserSetting(int contestID)
        {
            using (var entity = new PhotoMgrEntities(GenConnectionString()))
            {
                return entity.View_ContestUserSetting.Where(x=>x.ContestID == contestID).ToList();
            }
        }

        public static Round_NextRoundCapacity_Result Round_NextRoundCapacity(int roundID)
        {
            using (var entity = new PhotoMgrEntities(GenConnectionString()))
            {
                return entity.Round_NextRoundCapacity(roundID).ToList().First();
            }
        }

        public static void Round_UpdateForSubScore(int roundID, double scoreToRemark, double subscoreToRemark)
        {
            using (var entity = new PhotoMgrEntities(GenConnectionString()))
            {
                entity.Round_UpdateForSubScore(roundID, scoreToRemark, subscoreToRemark);
            }
        }

        public static List<View_RoundImage> Contest_ViewResult(int contestID)
        {
            using (var entity = new PhotoMgrEntities(GenConnectionString()))
            {
                int lastRoundID = entity.Rounds.Where(x => x.ContestID == contestID).OrderBy(x => x.RoundCapacity).First().RoundID;
                return entity.View_RoundImage.Where(x => x.RoundID == lastRoundID).OrderByDescending(x=>x.Score).ToList();
            }
        }
    }
}
